<template>
	  <div class="cropper_model">
		    <el-dialog   title="修改头像" width="378px" class="cropper_model_dlg" :visible.sync="visible" append-to-body
			:close-on-click-modal="false"   :close-on-press-escape="false"  >
			      <div class="cropper_content">
				    <div class="cropper" style="text-align: center;">
					<div class="flexrbc">
						<div style="width:300px; height: 300px;">
							<vueCropper ref="cropper" :img="options.img" :outputSize="options.outputSize"
								:outputType="options.outputType"  :info="options.info" :canScale="options.canScale"
								 :autoCrop="options.autoCrop" :autoCropWidth="options.autoCropWidth"
								:autoCropHeight="options.autoCropHeight" :fixed="options.fixed"
								:fixedBox="options.fixedBox" :fixedNumber="options.fixedNumber">
								          </vueCropper>
						</div>
						<el-slider :min='minNum' :step='step' :max="maxNum" v-model="value" vertical height="300px"
							@change="sliderChange">
						</el-slider>
					</div>  
					<div class="cropper_btns flexrsc">     
						<el-button type="text" @click="defaultImg" size="mini">恢复默认</el-button>
					</div> 
				</div>
			</div>
			     
			<div slot="footer" class="dialog-footer flexrec">
				<el-upload class="boxrDiu" :action="uploadFileUrl" :show-file-list="false" name='upFile'
					accept=".jpg,.png" :headers="uploadHeaders"
					:before-upload="beforeUpload" :on-success="uploadSuccess"  :on-error="uploadError">
					        <el-button round size="mini">重选</el-button>
				</el-upload>
				        <el-button round size="mini" type="primary" @click="uploadImg" :loading="loading"
					style="margin-left: 20px;">确定</el-button>
			</div>
			   
		</el-dialog>
		  </div>
</template>
<script>
	import {
		VueCropper
	} from "vue-cropper";
	import {
		getUploadFileUrl,
		getUploadVideoAndCover
	} from "@/api/model";
	import api from "@/api/http";

	export default {
		components: {
			VueCropper
		},
		data() {
			return {
				loading: false,
				value: 0,
				minNum: -10,
				maxNum: 10,
				step: 1,
				options: {
					img: "", // 裁剪图片的地址
					outputSize: 1, // 裁剪生成图片的质量
					outputType: "png", // 裁剪生成图片的格式
					info: true, // 裁剪框的大小信息
					canScale: true, // 图片是否允许滚动缩放
					autoCrop: true, // 是否默认生成截图狂
					autoCropWidth: 200, // 默认生成截图框宽度
					autoCropHeight: 200, // 默认生成截图框高度
					fixed: true, // 是否开启截图框宽高固定比例
					fixedNumber: [1, 1], // 截图框的宽高比例
					full: true, // 是否输出原图比例的截图
					fixedBox: true, // 固定截图框大小 不允许改变
					canMove: true, // 上传图片是否可以移动
					canMoveBox: false, // 截图框能否拖动
					original: true, // 上传图片按照原始比例渲染
					centerBox: false, // 截图框是否被限制在图片里面
					high: false, // 是否按照设备的dpr输出等比例图片
					infoTrue: true, // true为展示真实输出图片宽高false展示看到的截图框宽高
					maximgSize: 200, // 限制图片最大宽度和高度
					enlarge: 1, // 图片根据截图框输出比例倍数
					mode: "contain" // 图片默认渲染方式(contain, cover, 100px, 100% auto)
				},
				uploadHeaders: {}
			};
		},
		props: {
			visible: {
				type: Boolean,
				default: false
			},
		},
		watch: {
			value(newVal, oldVal) {
				// console.log(newVal, 'value---new')
				// console.log(oldVal, 'value---old');
				let num = newVal - oldVal
				if (num > 0) {
					setTimeout(() => {
						num--;
						this.changeScale(1);
					}, 10)
				} else {
					setTimeout(() => {
						num--;
						this.changeScale(-1);
					}, 10)
				}
			}
		},
		computed: {
			uploadFileUrl() {
				return getUploadFileUrl()
			}
		},
		mounted() {
			let token = sessionStorage.getItem('manageToken')
			this.uploadHeaders = {
				'Authorization': token
			}
		},
		methods: {
			uploadSuccess(response, file, fileList) {
				console.log(response);
				this.options.img = IP.resourUrl + response.message;
				this.imageUrl = IP.resourUrl + response.message
				this.imgPost = response.message
			},
			beforeUpload(file) { 
				const isLt2M = file.size / 1024 / 1024 < 2;
				const fileType = file.name.toLowerCase().split('.').pop();
				if (fileType == 'jpg' || fileType == 'png') {
					if (!isLt2M) {
						this.$message.error('上传图片大小不能超过 2MB!');
						return false
					}
				} else {
					this.$message({
						type: 'error',
						message: '仅允许上传图片(.jpg,.png)'
					})
					return false
				}
			
			},
			uploadError(err) {
				let errObj = JSON.parse(err.message)
				if (errObj.code == 500) {
					this.$message({
						type: 'error',
						message: errObj.message
					})
				}
			},
			sliderChange(e) {
				// console.log(e, '滑块滑动')
			},
			defaultImg() {
				this.$emit('defaultImg')
			}, 
			// base64转图片文件
			dataURLtoFile(dataurl, filename) {
				let arr = dataurl.split(",");
				let mime = arr[0].match(/:(.*?);/)[1];
				let bstr = atob(arr[1]);
				let len = bstr.length;
				let u8arr = new Uint8Array(len);
				while (len--) {
					u8arr[len] = bstr.charCodeAt(len);
				}
				return new File([u8arr], filename, {
					type: mime
				});
			},
			downLoad(type) {
				event.preventDefault();
				const aLink = document.createElement("a");
				if (type === "blob") {
					this.$refs.cropper.getCropBlob(data => {
						let downImg = window.URL.createObjectURL(data);
						aLink.download = "photo.png";
						aLink.href = downImg;
						aLink.click();
					});
				} else {
					this.$refs.cropper.getCropData(data => {
						let file = this.dataURLtoFile(data, "test");
						aLink.href = file;
						aLink.click();
					});
				}
			},
			// 左旋转
			rotateLeft() {
				this.$refs.cropper.rotateLeft();
			},
			// 右旋转
			rotateRight() {
				this.$refs.cropper.rotateRight();
			},
			// 放大缩小
			changeScale(num) {
				num = num || 1;
				// console.log(num, '放大缩小')
				this.$refs.cropper.changeScale(num);
			},
			// 实时预览
			previewImg(data) {
				// console.log(data, '实时预览')
				this.preview = data;
			},
			goUpload() {
				this.$emit("upAgain");
			},
			// 上传图片
			uploadImg() {
				let self = this;
				self.loading = true;
				this.$refs.cropper.getCropData(data => {
					// console.log(data,'data--是啥');
					let file = this.dataURLtoFile(data, "photo.png");
					// console.log(file, 'file---是啥');
					// 生成文件类型
					self.loading = false;
					let formData = new FormData();
					formData.append("upFile", file);
					api.getAddFileUrl(formData)
						.then((response) => {
							let res = response.data;
							let url = res.message; // 拿到图片url后发送图片消息
							this.value = 0;
							this.$emit("getFile", url)

						}).catch(err => {
							console.log(err, '错误')
						})
				})
			}
		}
	};
</script>

<style lang="less" scoped>
	.cropper_model_dlg {
		.cropper_content {
			margin: 0 auto;
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
		}
		.cropper {
			width: 338px;
			height: 338px;
		}
		.cropper_right {
			width: 300px;
			text-align: center;
		}

		.cropper_btns {
			margin-top: 20px;
		}
	}
</style>